package com.banksoft.admin.controller;


import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.bean.OrderStatus;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.Admin;
import com.banksoft.admin.entity.Order;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.entity.UserAddress;
import com.banksoft.admin.service.*;
import com.banksoft.common.BaseController;
import com.banksoft.common.ConfigHelper;
import com.banksoft.common.PageInfo;
import com.banksoft.util.DateUtil;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/31.
 */
@Controller
public class IndexController extends BaseController {

    private static Logger logger  = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
    UserAddressService userAddressService;
    @Autowired
    BaseService baseService;

    @RequestMapping("/admin")
    public String index(){
        return "login";
    }

    @RequestMapping("/main")
    public String main(){
        return "main";
    }

    @RequestMapping("/welcome")
    public String welcome(Model model,HttpServletRequest request){
        Admin admin = (Admin) this.getCurrentUser(request);

        return "welcome";
    }


    @RequestMapping("/queryArea")
    @ResponseBody
    public JSONObject queryArea(String startDate, String endDate, String province, String city, String area){
        try{
            if(StringUtil.isNotNull(startDate))
                startDate += " 00:00:00";

            if(StringUtil.isNotNull(endDate))
                endDate += " 23:59:59";

            Map map = new HashMap();
            if(StringUtil.isNotNull(startDate))
                map.put("startDate", DateUtil.getLongFormStrDate(startDate));
            if(StringUtil.isNotNull(endDate))
                map.put("endDate",DateUtil.getLongFormStrDate(endDate));
            map.put("province", province);
            map.put("city", city);
            map.put("area", area);
            map.put("status", new String[]{OrderStatus.Pay.name(),OrderStatus.Send.name(),OrderStatus.Suc.name()});

            List<Order> orderList = this.orderService.count(map);
            String totalMoney = "0";
            String totalPayMoney = "0";
            String totalBonus = "0";
            int gworder = 0;
            int sjorder = 0;
            int payorder = 0;
            int sendorder = 0;
            if(StringUtil.isNotEmpty(orderList)){
                for(Order order:orderList){
                    if("0".equals(order.getType())){
                        gworder++;
                        if(OrderStatus.Pay.name().equals(order.getStatus())){
                            payorder++;
                        }else if(OrderStatus.Send.name().equals(order.getStatus())){
                            sendorder++;
                        }
                    }else if("1".equals(order.getType())){
                        sjorder++;
                    }
                    totalMoney = StringNumber.add(totalMoney,order.getTotalMoney());
                    totalPayMoney = StringNumber.add(totalPayMoney,order.getPayAmount());
                    totalBonus = StringNumber.add(totalBonus,order.getBonusAmount());
                }
            }
            map.put("isMember","1");
            List<User> list = this.userService.list(map);
            int userTotal = list!=null?list.size():0;
            int userCnt = 0;
            int generalCnt = 0;
            int partnerCnt = 0;
            int goldCnt = 0;

            if(StringUtil.isNotEmpty(list)){
                for(User user:list){
                    if(user.getType().equals(MemberType.Gold.name())){
                        goldCnt ++;
                    }else if(user.getType().equals(MemberType.General.name())&&(!"1".equals(user.getIsPartner()))){
                        generalCnt++;
                    }else if(user.getType().equals(MemberType.General.name())&&("1".equals(user.getIsPartner()))){
                        partnerCnt++;
                    }else{
                        userCnt++;
                    }
                }
            }

            ConfigHelper instance = ConfigHelper.GetInstance();
            String txFee = instance.GetConfig("TxFee");
            String sxf = StringNumber.div(StringNumber.mul(totalMoney,txFee),"1000");
            String jsje = StringNumber.sub(totalMoney,sxf);

            Map result = new HashMap();
            result.put("orderCnt",orderList!=null?orderList.size():0);
            result.put("payOrder",payorder);
            result.put("sendOrder",sendorder);
            result.put("totalMoney",totalMoney);
            result.put("totalPayMoney",totalPayMoney);
            result.put("totalBonus",totalBonus);
            result.put("gwOrder",gworder);
            result.put("sjOrder",sjorder);
            result.put("userCnt",userCnt);
            result.put("goldCnt",goldCnt);
            result.put("generalCnt",generalCnt);
            result.put("partnerCnt",partnerCnt);
            result.put("userTotal",userTotal);
            result.put("sxf",sxf);
            result.put("jsje",jsje);


            //**********************************************
            //计算新增会员以及新增业绩
            String today = DateUtil.getFormatDate(new Date(),"yyyy-MM-dd");
            String startToday = today+" 00:00:00";
            String  endToday = today+" 23:59:59";
            map.put("startDate", DateUtil.getLongFormStrDate(startToday));
            map.put("endDate",DateUtil.getLongFormStrDate(endToday));

            List<Order> newOrderList = this.orderService.count(map);
            String newTotalMoney = "0";
            int newGworder = 0;
            int newSjorder = 0;

            if(StringUtil.isNotEmpty(newOrderList)){
                for(Order order:newOrderList){
                    if("0".equals(order.getType())){
                        newGworder++;
                    }else if("1".equals(order.getType())){
                        newSjorder++;
                    }
                    newTotalMoney = StringNumber.add(newTotalMoney,order.getTotalMoney());
                }
            }
            List<User> newlist = this.userService.list(map);
            int newUserTotal = newlist!=null?newlist.size():0;
            int newUserCnt = 0;
            int newGeneralCnt = 0;
            int newPartnerCnt = 0;
            int newGoldCnt = 0;

            if(StringUtil.isNotEmpty(newlist)){
                for(User user:newlist){
                    if(user.getType().equals(MemberType.Gold.name())){
                        newGoldCnt ++;
                    }else if(user.getType().equals(MemberType.General.name())&&(!"1".equals(user.getIsPartner()))){
                        newGeneralCnt++;
                    }else if(user.getType().equals(MemberType.General.name())&&("1".equals(user.getIsPartner()))){
                        newPartnerCnt++;
                    }else{
                        newUserCnt++;
                    }
                }
            }

            String newSxf = StringNumber.div(StringNumber.mul(newTotalMoney,txFee),"1000");
            String newJy = StringNumber.sub(newTotalMoney,newSxf);

            result.put("newOrderCnt",newOrderList!=null?newOrderList.size():0);
            result.put("newTotalMoney",newTotalMoney);
            result.put("newGworder",newGworder);
            result.put("newSjorder",newSjorder);
            result.put("newUserTotal",newUserTotal);
            result.put("newGoldCnt",newGoldCnt);
            result.put("newGeneralCnt",newGeneralCnt);
            result.put("newPartnerCnt",newPartnerCnt);
            result.put("newUserCnt",newUserCnt);
           // result.put("newSxf",newSxf);
            //result.put("newJy",newJy);
            return this.FmtResult(true,null,result);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,null,null);
    }

    @RequestMapping("/showDetails")
    public String showDetails(Model model,String today,String index,String startDate,String endDate,String province,String city,String area){
        model.addAttribute("index",index);
        if(StringUtil.isNotNull(today)&&"1".equals(today)){
            model.addAttribute("startDate",DateUtil.getFormatDate(new Date(),"yyyy-MM-dd"));
            model.addAttribute("endDate",DateUtil.getFormatDate(new Date(),"yyyy-MM-dd"));
        }else{
            model.addAttribute("startDate",startDate);
            model.addAttribute("endDate",endDate);
        }
        model.addAttribute("province",province);
        model.addAttribute("city",city);
        model.addAttribute("area",area);
        return "welcome_list";
    }

    @RequestMapping("/showDetailsData")
    @ResponseBody
    public Object showDetailsData(PageInfo pageInfo,String index,String startDate,String endDate,String province,String city,String area){
        Map<String,Object> map = new HashMap<>();
        if(StringUtil.isNotNull(startDate))
            startDate += " 00:00:00";
        if(StringUtil.isNotNull(endDate))
            endDate += " 23:59:59";

        if(StringUtil.isNotNull(startDate))
            map.put("startDate", DateUtil.getLongFormStrDate(startDate));
        if(StringUtil.isNotNull(endDate))
            map.put("endDate",DateUtil.getLongFormStrDate(endDate));
        if("1".equals(index)){
            map.put("type",MemberType.Customer.name());
        }else if("2".equals(index)){
            map.put("type",MemberType.Gold.name());
        }else if("3".equals(index)){
            map.put("type",MemberType.General.name());
        }else if("4".equals(index)){
            map.put("type",MemberType.General.name());
            map.put("isPartner","1");
        }

        map.put("province",province);
        map.put("city",city);
        map.put("area",area);
        map.put("size",16);
        pageInfo.setParams(map);

        Integer total = userService.countPage(pageInfo.getParams());
        List<User> list = userService.searchByPage(pageInfo.getParams());
        if("3".equals(index)){
            map.put("isPartner","1");
            pageInfo.setParams(map);
            Integer partnerCnt = userService.countPage(pageInfo.getParams());
            total -= partnerCnt;
        }
        if(StringUtil.isNotEmpty(list)){
            for(User user:list){
                    List<UserAddress> userAddressList = this.userAddressService.listByUserId(user.getId());
                    if (StringUtil.isNotEmpty(userAddressList)) {
                        UserAddress userAddress = userAddressList.get(0);
                        if (!StringUtil.isNotNull(user.getCardName())) {
                            user.setCardName(userAddress.getUserName());
                        }
                        if (!StringUtil.isNotNull(user.getMobile())) {
                            user.setMobile(userAddress.getTelephone());
                        }
                        user.setUserAreaName(userAddress.getProvinceName() + userAddress.getCityName() + userAddress.getAreaName() + (userAddress.getAddress()!=null?userAddress.getAreaName():""));
                    }
                    //查找推荐人
                    User upuser = this.baseService.findById(UserDao.class, user.getRecommendId());
                    if (upuser != null) {
                        if (StringUtil.isNotNull(upuser.getCardName())) {//真实姓名存在
                            user.setTdyj(upuser.getCardName());
                        } else {
                            List<UserAddress> upUserAddresses = this.userAddressService.listByUserId(user.getRecommendId());
                            if (StringUtil.isNotEmpty(upUserAddresses)) {//收货人存在
                                UserAddress address = upUserAddresses.get(0);
                                user.setTdyj(address.getUserName());
                            } else {//收货人不存在
                                user.setTdyj(upuser.getNickName() + "(" + upuser.getAccount() + ")");
                            }
                        }
                    }
            }
        }
        pageInfo.setTotal(total);
        pageInfo.setResult(list);

        return this.getPageResult(pageInfo);
    }

    @RequestMapping("/showOrderDetails")
    public String showOrderDetails(Model model,String today,String type,String status,String startDate,String endDate,String province,String city,String area){
        model.addAttribute("type",type);
        model.addAttribute("status",status);
        if(StringUtil.isNotNull(today)&&"1".equals(today)){
            model.addAttribute("startDate",DateUtil.getFormatDate(new Date(),"yyyy-MM-dd"));
            model.addAttribute("endDate",DateUtil.getFormatDate(new Date(),"yyyy-MM-dd"));
        }else{
            model.addAttribute("startDate",startDate);
            model.addAttribute("endDate",endDate);
        }
        model.addAttribute("province",province);
        model.addAttribute("city",city);
        model.addAttribute("area",area);
        return "welcome_order_list";
    }

    @RequestMapping("/showOrderDetailsData")
    @ResponseBody
    public JSONObject showOrderDetailsData(String type,String status,PageInfo pageInfo,String startDate,String endDate,String province,String city,String area ){
        Map<String,Object> map = new HashMap<>();
        if(StringUtil.isNotNull(startDate))
            startDate += " 00:00:00";
        if(StringUtil.isNotNull(endDate))
            endDate += " 23:59:59";

        if(StringUtil.isNotNull(startDate))
            map.put("startDate", DateUtil.getLongFormStrDate(startDate));
        if(StringUtil.isNotNull(endDate))
            map.put("endDate",DateUtil.getLongFormStrDate(endDate));

        if(StringUtil.isNotNull(type)&&!type.equals("2")){
            map.put("type",type);
        }
        if(StringUtil.isNotNull(status)&&!status.equals("0")){
            map.put("status",new String[]{status});
        }else{//全部状态
            map.put("status",new String[]{OrderStatus.Pay.name(),OrderStatus.Send.name(),OrderStatus.Suc.name()});
        }
        map.put("province",province);
        map.put("city",city);
        map.put("area",area);
        map.put("size",16);
        pageInfo.setParams(map);

        Integer total = orderService.countQueryPage(pageInfo.getParams());
        List<Order> list = orderService.queryByPage(pageInfo.getParams());

        pageInfo.setTotal(total);
        pageInfo.setResult(list);

        return this.getPageResult(pageInfo);
    }


    @RequestMapping("/wx/checkNewOrder")
    @ResponseBody
    public JSONObject checkNewOrder(){
        try {
            Long end = System.currentTimeMillis();
            Long start = end - (60*1000);

            Map map = new HashMap();
            map.put("startDate",start);
            map.put("endDate",end);
            map.put("status",new String[]{OrderStatus.Pay.name()});
            List<Order> list = orderService.query(map);
            if(StringUtil.isNotEmpty(list))
                return this.FmtResult(true,null,null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,null,null);
    }
}
